package hierarchy

import (
	"errors"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/common/request"
	"gitcode.com/G-YT/ANN/server/model/hierarchy"
	hierarchyReq "gitcode.com/G-YT/ANN/server/model/hierarchy/request"
	hierarchyRes "gitcode.com/G-YT/ANN/server/model/hierarchy/response"
	"gorm.io/gorm"
	"strings"
)

type LevelTwoService struct {
}

// CreateLevelTwo 创建LevelTwo记录
// Author [piexlmax](https://github.com/piexlmax)
func (levelTwoService *LevelTwoService) CreateLevelTwo(levelTwo *hierarchy.LevelTwo) (err error) {
	err = global.GVA_DB.Create(levelTwo).Error
	return err
}

// DeleteLevelTwo 删除LevelTwo记录
// Author [piexlmax](https://github.com/piexlmax)
func (levelTwoService *LevelTwoService) DeleteLevelTwo(levelTwo hierarchy.LevelTwo) (err error) {
	if !errors.Is(global.GVA_DB.Where("level_two_id = ?", levelTwo.ID).First(&hierarchy.FdArticleVideo{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("此目錄有視頻類型文章存在禁止刪除")
	}
	if !errors.Is(global.GVA_DB.Where("level_two_id = ?", levelTwo.ID).First(&hierarchy.FdArticleAudio{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("此目錄有音頻類型文章存在禁止刪除")
	}
	if !errors.Is(global.GVA_DB.Where("level_two_id = ?", levelTwo.ID).First(&hierarchy.FdArticleGraphic{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("此目錄有圖文類型文章存在禁止刪除")
	}
	if err = global.GVA_DB.Delete(&levelTwo).Error; err != nil {
		return errors.New("刪除失敗")
	}
	return
}

// DeleteLevelTwoByIds 批量删除LevelTwo记录
// Author [piexlmax](https://github.com/piexlmax)
func (levelTwoService *LevelTwoService) DeleteLevelTwoByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]hierarchy.LevelTwo{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateLevelTwo 更新LevelTwo记录
// Author [piexlmax](https://github.com/piexlmax)
func (levelTwoService *LevelTwoService) UpdateLevelTwo(levelTwo hierarchy.LevelTwo) (err error) {
	err = global.GVA_DB.Save(&levelTwo).Error
	return err
}

// GetLevelTwo 根据id获取LevelTwo记录
// Author [piexlmax](https://github.com/piexlmax)
func (levelTwoService *LevelTwoService) GetLevelTwo(id uint) (levelTwo hierarchy.LevelTwo, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&levelTwo).Error
	return
}

// GetLevelTwoInfoList 分页获取LevelTwo记录
// Author [piexlmax](https://github.com/piexlmax)
func (levelTwoService *LevelTwoService) GetLevelTwoInfoList(info hierarchyReq.LevelTwoSearch) (list []hierarchy.LevelTwo, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&hierarchy.LevelTwo{})
	var levelTwos []hierarchy.LevelTwo
	if info.LevelOneID != 0 {
		db = db.Where("level_one_id = ?", info.LevelOneID)
	}
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}

	if info.Key != "" {
		db = db.Where("key = ?", info.Key)
	}
	if info.Value != "" {
		db = db.Where("value = ?", info.Value)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&levelTwos).Error
	return levelTwos, total, err
}

// GetLevelTwoListByIds 根据ID集合获取二级目录列表
// Author [g-qs](https://gitee.com/g-qs)
func (levelTwoService *LevelTwoService) GetLevelTwoListByIds(info hierarchyReq.LevelTwoIdsSearch) (list []hierarchy.LevelTwo, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&hierarchy.LevelTwo{})
	var levelTwos []hierarchy.LevelTwo
	if info.IDs != "" {
		IDsStr := strings.Trim(info.IDs, "[]")
		IDsArr := strings.Split(IDsStr, ",")
		db = db.Where("id IN (?)", IDsArr)
	}
	if info.LevelOneID != 0 {
		db = db.Where("level_one_id = ?", info.LevelOneID)
	}
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}

	if info.Key != "" {
		db = db.Where("key = ?", info.Key)
	}
	if info.Value != "" {
		db = db.Where("value = ?", info.Value)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Debug().Find(&levelTwos).Error
	return levelTwos, total, err
}

// GetTwoLevelListByWhere 获取LevelTwo记录
// Author [g-qs](https://github.com/g-qs)
func (levelTwoService *LevelTwoService) GetTwoLevelListByWhere(info hierarchyReq.LevelTwoSearch) (list []hierarchyRes.TwoLevel, err error) {
	var TwoLevel []hierarchyRes.TwoLevel
	err = global.GVA_DB.Model(&hierarchy.LevelTwo{}).Where("level_one_id = ?", info.LevelOneID).Find(&TwoLevel).Error
	return TwoLevel, err
}

func (levelTwoService *LevelTwoService) GetArticle(pageInfo hierarchyReq.LevelTwoArticleSearch, userID uint) (list []hierarchy.LevelThreeReq, err error) {
	var levelThrees []hierarchy.LevelThreeWithArt
	db := global.GVA_DB.Model(&hierarchy.LevelThree{}).
		Preload("Graphics", "status = 1", func(db *gorm.DB) *gorm.DB {
			return db.Preload("FdArticleLike", "user_id = ? and fd_article_type = ?", userID, "graphic").
				Preload("FdArticleCollect", "user_id = ? and fd_article_type = ?", userID, "graphic").
				Preload("LevelOne").Preload("LevelTwo").Preload("LevelThree").Order("created_at desc")
		}).
		Preload("Audios", "status = 1", func(db *gorm.DB) *gorm.DB {
			return db.Preload("FdArticleLike", "user_id = ? and fd_article_type = ?", userID, "audio").
				Preload("FdArticleCollect", "user_id = ? and fd_article_type = ?", userID, "audio").
				Preload("LevelOne").Preload("LevelTwo").Preload("LevelThree").Order("created_at desc")
		}).
		Preload("Videos", "status = 1", func(db *gorm.DB) *gorm.DB {
			return db.Preload("FdArticleLike", "user_id = ? and fd_article_type = ?", userID, "video").
				Preload("FdArticleCollect", "user_id = ? and fd_article_type = ?", userID, "video").
				Preload("LevelOne").Preload("LevelTwo").Preload("LevelThree").Order("created_at desc")
		}).Where("level_two_id = ?", pageInfo.ID)
	err = db.Find(&levelThrees).Error

	for i := range levelThrees {
		var l interface{}
		switch pageInfo.Type {
		case hierarchy.AUDIO:
			for i2 := range levelThrees[i].Audios {
				//if levelThrees[i].Audios[i2].PV != "" {
				//	num, _ := strconv.ParseFloat(levelThrees[i].Audios[i2].PV, 64)
				//	if num < 200 {
				//		// 点赞量 * 0.5 拼接“w+”
				//		likes := int(num * 0.5)
				//		levelThrees[i].Audios[i2].PraiseNum = fmt.Sprintf("%dw+", likes)
				//		// 浏览量直接拼接“w+”
				//		levelThrees[i].Audios[i2].PV = fmt.Sprintf("%dw+", int(num))
				//	} else {
				//		levelThrees[i].Audios[i2].PraiseNum = "100w+"
				//		levelThrees[i].Audios[i2].PV = fmt.Sprintf("%dw+", int(num))
				//	}
				//} else {
				//	levelThrees[i].Audios[i2].PV = "1w+"
				//	levelThrees[i].Audios[i2].PraiseNum = "999+"
				//}
				if levelThrees[i].Audios[i2].FdArticleCollect != nil {
					levelThrees[i].Audios[i2].IsCollect = true
				} else {
					levelThrees[i].Audios[i2].IsCollect = false
				}
				if levelThrees[i].Audios[i2].FdArticleLike != nil {
					levelThrees[i].Audios[i2].IsPraise = true
				} else {
					levelThrees[i].Audios[i2].IsPraise = false
				}
			}
			l = levelThrees[i].Audios
		case hierarchy.VIDEO:
			for i2 := range levelThrees[i].Videos {
				//if levelThrees[i].Videos[i2].PV != "" {
				//	num, _ := strconv.ParseFloat(levelThrees[i].Videos[i2].PV, 64)
				//	if num < 200 {
				//		// 点赞量 * 0.5 拼接“w+”
				//		likes := int(num * 0.5)
				//		levelThrees[i].Videos[i2].PraiseNum = fmt.Sprintf("%dw+", likes)
				//		// 浏览量直接拼接“w+”
				//		levelThrees[i].Videos[i2].PV = fmt.Sprintf("%dw+", int(num))
				//	} else {
				//		levelThrees[i].Videos[i2].PraiseNum = "100w+"
				//		levelThrees[i].Videos[i2].PV = fmt.Sprintf("%dw+", int(num))
				//	}
				//} else {
				//	levelThrees[i].Videos[i2].PV = "1w+"
				//	levelThrees[i].Videos[i2].PraiseNum = "999+"
				//}
				if levelThrees[i].Videos[i2].FdArticleCollect != nil {
					levelThrees[i].Videos[i2].IsCollect = true
				} else {
					levelThrees[i].Videos[i2].IsCollect = false
				}
				if levelThrees[i].Videos[i2].FdArticleLike != nil {
					levelThrees[i].Videos[i2].IsPraise = true
				} else {
					levelThrees[i].Videos[i2].IsPraise = false
				}
			}
			l = levelThrees[i].Videos
		case hierarchy.GRAPHIC:
			for i2 := range levelThrees[i].Graphics {
				//if levelThrees[i].Graphics[i2].PV != "" {
				//	num, _ := strconv.ParseFloat(levelThrees[i].Graphics[i2].PV, 64)
				//	if num < 200 {
				//		// 点赞量 * 0.5 拼接“w+”
				//		likes := int(num * 0.5)
				//		levelThrees[i].Graphics[i2].PraiseNum = fmt.Sprintf("%dw+", likes)
				//		// 浏览量直接拼接“w+”
				//		levelThrees[i].Graphics[i2].PV = fmt.Sprintf("%dw+", int(num))
				//	} else {
				//		levelThrees[i].Graphics[i2].PraiseNum = "100w+"
				//		levelThrees[i].Graphics[i2].PV = fmt.Sprintf("%dw+", int(num))
				//	}
				//} else {
				//	levelThrees[i].Graphics[i2].PV = "1w+"
				//	levelThrees[i].Graphics[i2].PraiseNum = "999+"
				//}
				if levelThrees[i].Graphics[i2].FdArticleCollect != nil {
					levelThrees[i].Graphics[i2].IsCollect = true
				} else {
					levelThrees[i].Graphics[i2].IsCollect = false
				}
				if levelThrees[i].Graphics[i2].FdArticleLike != nil {
					levelThrees[i].Graphics[i2].IsPraise = true
				} else {
					levelThrees[i].Graphics[i2].IsPraise = false
				}
			}
			l = levelThrees[i].Graphics
		default:
			for i2 := range levelThrees[i].Graphics {
				//if levelThrees[i].Videos[i2].PV != "" {
				//	num, _ := strconv.ParseFloat(levelThrees[i].Graphics[i2].PV, 64)
				//	if num < 200 {
				//		// 点赞量 * 0.5 拼接“w+”
				//		likes := int(num * 0.5)
				//		levelThrees[i].Graphics[i2].PraiseNum = fmt.Sprintf("%dw+", likes)
				//		// 浏览量直接拼接“w+”
				//		levelThrees[i].Graphics[i2].PV = fmt.Sprintf("%dw+", int(num))
				//	} else {
				//		levelThrees[i].Graphics[i2].PraiseNum = "100w+"
				//		levelThrees[i].Graphics[i2].PV = fmt.Sprintf("%dw+", int(num))
				//	}
				//} else {
				//	levelThrees[i].Graphics[i2].PV = "1w+"
				//	levelThrees[i].Graphics[i2].PraiseNum = "999+"
				//}
				if levelThrees[i].Graphics[i2].FdArticleCollect != nil {
					levelThrees[i].Graphics[i2].IsCollect = true
				} else {
					levelThrees[i].Graphics[i2].IsCollect = false
				}
				if levelThrees[i].Graphics[i2].FdArticleLike != nil {
					levelThrees[i].Graphics[i2].IsPraise = true
				} else {
					levelThrees[i].Graphics[i2].IsPraise = false
				}
			}
			l = levelThrees[i].Graphics
		}
		list = append(list, hierarchy.LevelThreeReq{
			ID:         levelThrees[i].ID,
			LevelTwoID: levelThrees[i].LevelTwoID,
			Value:      levelThrees[i].Value,
			Key:        levelThrees[i].Key,
			List:       l,
		})
	}

	return list, err
}
